package com.ido.otaclient.nordic;

import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;


import com.ido.otaclient.R;
import com.ido.otaclient.Status;
import com.ido.otaclient.StatusDownload;
import com.ido.otaclient.StatusUpgrade;
import com.ido.otaclient.api.OkhttpUtil;
import com.ido.otaclient.base.ApiConstant;
import com.ido.otaclient.base.Constant;
import com.ido.otaclient.base.IDLog;
import com.ido.otaclient.env.AppEnv;
import com.ido.otaclient.module.Veneer;
import com.ido.otaclient.util.AppExecutors;
import com.ido.otaclient.util.FileUtil;
import com.ido.otaclient.util.ResourceUtil;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpPost;
import com.koushikdutta.async.http.AsyncHttpResponse;
import com.koushikdutta.async.http.body.MultipartFormDataBody;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (c) 2019 深圳市爱都科技有限公司. All rights reserved.
 *
 * @Author: xyb
 * @CreateDate: 2020-02-28 09:34
 * @description
 */
public class NordicPresenter implements NordicContract.Presenter{
    private static final String TAG = "NordicPresenter";
    private NordicContract.View mView;


    public NordicPresenter(NordicContract.View mView) {
        this.mView = mView;
    }

    @Override
    public void start() {

    }

    @Override
    public void release() {

    }

    @Override
    public void uploadAndConfirmFile(List<Veneer> veneerList) {
        String filePath = mView.getFilePath();
        String fileVersion = mView.getChooseFileVersion();
        if(TextUtils.isEmpty(filePath)){
            mView.showMessage(ResourceUtil.getString(R.string.upload_choose_file));
            return;
        }
        if(TextUtils.isEmpty(fileVersion)){
            mView.showMessage(ResourceUtil.getString(R.string.upload_input_version));
            return;
        }
        if(TextUtils.isEmpty(mView.getDeviceId())){
            mView.showMessage(ResourceUtil.getString(R.string.please_input_device_id));
            return;
        }
        if(veneerList == null || veneerList.size() == 0){
            mView.showMessage(ResourceUtil.getString(R.string.veneer_not_found));
            return;
        }
        for(Veneer veneer : veneerList) {
            if (!TextUtils.isEmpty(veneer.getIp())) {
                Log.d(TAG,veneer.toString());
            }
        }
        // 上传一个ip之后在上传另一个
        boolean isComplete = true;
        mView.showLoading();
        //判断是否需要下发固件
        for(Veneer veneer : veneerList){
            IDLog.d(TAG, "uploadAndConfirmFile: " + veneer.toString());
            if(!TextUtils.isEmpty(veneer.getIp()) &&
                    veneer.getDownloadStatus() == StatusDownload.START.getCode()
                    && veneer.getFailConnectCount() < 3){
                //String url = ApiConstant.URL_HEAD + veneer.getIp() +":"+ Constant.HTTP_PORT;
                String url = ApiConstant.URL_HEAD + veneer.getIpPort();
                uploadFile(url,filePath,fileVersion,veneer.getIpPort());
                isComplete = false;
                break;
            }
        }
        if(isComplete){
            //todo 判断是否有断开的单板有的话要
            int failCount = 0;
            for(int i = 0;i < veneerList.size();i++){
                Veneer veneer = veneerList.get(i);
                if(veneer.getUpdateStatus() == StatusUpgrade.FAIL.getCode()){
                    failCount ++;
                }
            }
            if(failCount > 0){
                mView.hideLoading();
                mView.showConfirm(String.valueOf(failCount));
            }else {
                mView.hideLoading();
                saveUploadType();
            }

        }
    }

    @Override
    public void uploadFile(String url, String filePath, String fileVersion, String ipPort) {
        long size = FileUtil.getFileSize(filePath);
        String sizeStr = String.valueOf(size);

        AsyncHttpPost post = new AsyncHttpPost(url + "/upload");
        MultipartFormDataBody body = new MultipartFormDataBody();
        body.addFilePart("text.zip", new File(filePath));
        // 文件名传递
        body.addStringPart("foo", "upload.zip");
        post.setBody(body);
        AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
            @Override
            public void onCompleted(Exception ex, AsyncHttpResponse source, String result) {
                if (ex != null) {
                    mView.hideLoading();
                    //WaitingDialog.hideDialog();
                    AppExecutors.globalAppExecutors().mainThread().execute(()
                            -> updateVeneer(ipPort));
                    ex.printStackTrace();
                    return;
                }
                System.out.println("Server says: " + result);
                //确认成功
                confirmUploadFile(url,sizeStr,fileVersion,filePath,ipPort);
            }
        });
    }

    /**
     * 文件上传失败更新单板信息
     * @param ipPort 请求的ip
     */
    private void updateVeneer(String ipPort) {
        List<Veneer> veneerList = new ArrayList<>();
        veneerList.addAll(mView.getVeneerList());
        for(int i= 0;i < veneerList.size();i++){
            Veneer veneer = veneerList.get(i);
            if(ipPort.equals(veneer.getIpPort())){
                int failCount = veneer.getFailConnectCount();
                veneer.setFailConnectCount(++failCount);
                veneer.setDownloadStatus(StatusDownload.START.getCode());
                if(failCount >= 3){
                    veneer.setUpdateStatus(StatusUpgrade.FAIL.getCode());
                }
                veneerList.set(i,veneer);
                mView.setVeneerList(veneerList);
            }
        }
        mView.showConfirmCancel();
    }

    @Override
    public void showChooseFile(Uri uri) {
        String mPath = "";
        if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开
            mPath = uri.getPath();
        } else {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
                mPath = FileUtil.getPath(AppEnv.instance().getContext(), uri);
            } else {//4.4以下下系统调用方法
                //path = FileUtil.getRealPathFromURI(this, uri);
            }
        }

        mView.setChooseDrawable();
        mView.setFilePath(mPath);
        mView.showTvChooseFile(true);
        if(!TextUtils.isEmpty(mPath))
            mView.setTvChooseFileName(FileUtil.getFileNameFromPath(mPath));
    }

    @Override
    public void confirmUploadFile(String url, String sizeStr, String fileVersion,
                                  String filePath, String ipPort) {
        IDLog.d(TAG, "confirmUploadFile: " + url + ","+ipPort);
        String name = FileUtil.getFileNameFromPath(filePath);
        StringBuffer sb = new StringBuffer();
        sb.append(url);
        sb.append("/");
        sb.append(ApiConstant.METHOD_CONFIRM_FIREWARE);
        sb.append("?");
        sb.append("size=");
        sb.append(sizeStr);
        sb.append("&");
        sb.append("taskType=");
        sb.append(Constant.TASK_NAME_NORDIC);
        sb.append("&");
        sb.append("fileName=");
        sb.append(name);
        sb.append("&");
        sb.append("uploadType=");
        sb.append(mView.getUpdateType());
        sb.append("&");
        sb.append("fileVersion=");
        sb.append(fileVersion);
        sb.append("&");
        sb.append("deviceId=");
        sb.append(mView.getDeviceId());
        url = sb.toString();
        OkhttpUtil okhttpUtil = OkhttpUtil.getInstance();
        okhttpUtil.getSyn(url, new OkhttpUtil.OkhttpCallback() {
            @Override
            public void onSuccess(String success) {
                AppExecutors.globalAppExecutors().mainThread().execute(() -> updateVeneer(success, ipPort));

                //AppExecutors.globalAppExecutors().mainThread().execute(()
                  //      ->uploadAndConfirmFile(mView.getVeneerList()));
            }

            @Override
            public void onFailed(String message) {
                //WaitingDialog.hideDialog();
                mView.hideLoading();
                Log.d(TAG,message);

                mView.showConfirmCancel();
            }
        });
    }

    /**
     * 文件大小一才下发文件给下一个
     * @param success
     * @param url
     */
    private void updateVeneer(String success,String url) {
        IDLog.d(TAG, "updateVeneer: " + success + ","+ url);
        try {
            JSONObject jsonObject = new JSONObject(success);
            String errCode = jsonObject.getString("errcode");
            String errMsg = jsonObject.getString("errmsg");
            if(Integer.parseInt(errCode) == Status.REQUEST_OK.getRequestStatus()){
                List<Veneer> veneerList = new ArrayList<>();
                veneerList.addAll(mView.getVeneerList());
                for(int i= 0;i < veneerList.size();i++){
                    Veneer veneer = veneerList.get(i);
                    if(url.equals(veneer.getIpPort())){
                        veneer.setDownloadStatus(StatusDownload.COMPLETE.getCode());
                        veneerList.set(i,veneer);
                        mView.setVeneerList(veneerList);
                        uploadAndConfirmFile(mView.getVeneerList());
                    }
                }
            }else {
                mView.showConfirmCancel();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void initData() {
        //保存nordic 文件配置信息
        NordicConfigPerfence nordicConfigPerfence = NordicConfigPerfence.getInstance();
        NordicConfig nordicConfig = nordicConfigPerfence.getNordicConfig();
        if(nordicConfig != null){
            IDLog.d(TAG, "initData: " + nordicConfig.toString());
            if(TextUtils.isEmpty(nordicConfig.getFirewareNormalName())){
                mView.showTvChooseFile(false);
            }else {
                mView.setChooseDrawable();
                mView.showTvChooseFile(true);
                mView.setTvChooseFileName(nordicConfig.getFirewareNormalName());
                mView.setFilePath(nordicConfig.getFirewareWarePath());
            }
            mView.setDeviceId(nordicConfig.getDeviceId());
            String updateType = nordicConfig.getUploadName();
            if(TextUtils.isEmpty(updateType)){
                mView.checkApplication();
                mView.setUpdateType(ApiConstant.UPDATE_TYPE_APPLICATION);
            }
            else if(updateType.equals(ApiConstant.UPDATE_TYPE_APPLICATION)){
                mView.checkApplication();
                mView.setUpdateType(ApiConstant.UPDATE_TYPE_APPLICATION);
            }else {
                mView.checkBootloader();
                mView.setUpdateType(ApiConstant.UPDATE_TYPE_BOOTLOADER);
            }
            mView.setFileVersion(nordicConfig.getFirewareNormalVersion());
        }
    }

    /**
     * 保存
     */
    private void saveUploadType() {
        //UploadConfigPreference uploadConfigPerfence = UploadConfigPreference.getInstance();
        NordicConfigPerfence nordicConfigPerfence = NordicConfigPerfence.getInstance();
        String filePath = mView.getFilePath();
        String fileName = FileUtil.getFileNameFromPath(filePath);
        String fileVersion = mView.getChooseFileVersion();
        //保存当前的配置任务
        //UploadConfig uploadConfig = new UploadConfig();
        //uploadConfig.setTaskName(Constant.TASK_NAME_NORDIC);
        //uploadConfigPerfence.saveUploadConfig(uploadConfig);

        //保存nordic 文件配置信息
        NordicConfig nordicConfig = new NordicConfig();
        //保存
        nordicConfig.setTaskName(Constant.TASK_NAME_NORDIC);
        nordicConfig.setUploadName(mView.getUpdateType());
        nordicConfig.setFirewareNormalName(fileName);
        nordicConfig.setFirewareNormalVersion(fileVersion);
        nordicConfig.setFirewareWarePath(mView.getFilePath());
        nordicConfig.setDeviceId(mView.getDeviceId());
        IDLog.d(TAG, "saveUploadType: " + nordicConfig.toString());
        nordicConfigPerfence.saveUploadConfig(nordicConfig);
        mView.showMessage(ResourceUtil.getString(R.string.upload_file_success));
        mView.back();
    }
}
